package com.tvunetworks.center.device.config.datasource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;


/**
 * @author Ethan
 * @data: 2021/6/15 14:12
 * @program:
 * @description:
 */
@Aspect
@Component
@Slf4j
@Order(0)
public class DataSourceAop {

	@Value("${readSuffix}")
	private String readSuffix;

	/**
	 *
	 * @param joinPoint joinPoint
	 */
	@Before("execution(* com.tvunetworks.center.user.group.service..*.*(..))")
	public void switchDataSourceType(JoinPoint joinPoint) {
		//判断是否是Transactional方法
		if (joinPoint.getSignature() instanceof MethodSignature) {
			Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
			if (method.isAnnotationPresent(Transactional.class)) {
				DataSourceContextHolder.write();
				return;
			}
		}

		String[] readSuffixArr = readSuffix.split(",");
		for (String read : readSuffixArr) {
			String name = joinPoint.getSignature().getName().toLowerCase();
			if (name.startsWith(read)) {
				log.debug("dataSource switch to: Read");
				DataSourceContextHolder.read();
				return;
			}
		}
		log.debug("dataSource switch to: Write");
		DataSourceContextHolder.write();
	}

}